package com.koi.common.utils.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.koi.common.utils.string.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 * @description [全局异常解析JSON]
 * @author ･ᴗ･
 */
@Slf4j
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();


    /**
     * @description [JackSon转换为JSON数据]
     * @author ･ᴗ･
     */
    public static <T> String toJsonString(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("数据转换失败：{}", e.getMessage());
            return null;
        }
    }

    /**
     * @description [将JSON字符串转换为指定类型的对象]
     * @param json JSON字符串
     * @param valueType 要转换的目标类型
     * @return 返回转换后的对象
     * @author ･ᴗ･
     */
    public static <T> T parseObject(String json, Class<T> valueType) {
        if (StringUtil.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("KOI1", "KOI1");
        map.put("KOI2", "KOI2");
        String jsonString = JsonUtil.toJsonString(map);
        System.out.println("jsonString：" + jsonString);
        Object object = JsonUtil.parseObject(jsonString, Object.class);
        System.out.println("parseObject：" + object);
    }

}
